package com.example.minilark.presentation.contacts

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.minilark.data.model.Contact
import com.example.minilark.data.oss.OSSManager
import com.example.minilark.service.ChatApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class ContactsState(
    val contacts: List<Contact> = emptyList(),
    val isLoading: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class ContactsViewModel @Inject constructor(
    private val chatApiService: ChatApiService,
    private val ossManager: OSSManager,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    private val _state = MutableStateFlow(ContactsState())
    val state: StateFlow<ContactsState> = _state.asStateFlow()

    private val username: String = savedStateHandle.get<String>("username") ?: ""

    init {
        if (username.isNotBlank()) {
            loadContacts()
        }
    }

    fun loadContacts() {
        viewModelScope.launch {
            try {
                println("[ContactsViewModel] 开始加载联系人列表")
                _state.update { it.copy(isLoading = true) }
                
                val allUsers = chatApiService.getContacts(username)
                // 过滤掉当前用户
                val contacts = allUsers.filter { it.username != username }
                println("[ContactsViewModel] 成功获取到 ${contacts.size} 个联系人")
                
                _state.update { it.copy(
                    contacts = contacts,
                    isLoading = false,
                    error = null
                ) }
            } catch (e: Exception) {
                println("[ContactsViewModel] 加载联系人列表失败: ${e.message}")
                e.printStackTrace()
                _state.update { it.copy(
                    isLoading = false,
                    error = e.message ?: "Failed to load contacts"
                ) }
            }
        }
    }

    fun refreshContacts() {
        loadContacts()
    }

    suspend fun getSignedImageUrl(objectKey: String): String {
        return ossManager.getObjectUrl(objectKey)
    }
} 